package com.app.business.web.business.property;

import com.app.business.model.AzProject;
import com.app.business.model.House;
import com.app.business.model.HousePersonForProperty;
import com.app.business.service.*;
import com.app.system.jpa.PageBean;
import com.app.system.log4j2.LogUtils;
import com.app.system.permission.model.DataDict;
import com.app.system.permission.model.UserInfo;
import com.app.system.permission.service.DataDictService;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.WebUtils;
import com.app.system.utils.dataType.BigDecimalUtils;
import com.app.system.utils.dataType.DateUtils;
import com.app.system.utils.dataType.StringUtils;
import com.app.system.utils.exception.AjaxException;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.app.system.utils.page.LayUiUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import freemarker.template.Configuration;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by ddz on 2020/9/1.
 */
@Controller
@RequestMapping("/business/property/housePersonForProperty/*")
@SuppressWarnings("all")
public class HousePersonForPropertyController {

    @Autowired
    private DataDictService dataDictService;
    @Autowired
    private HouseService houseService;
    @Autowired
    private HousePersonForPropertyService housePersonForPropertyService;
    @Autowired
    private AzProjectService azProjectService;
    @Autowired
    private BuyHousePersonService buyHousePersonService;
    @Autowired
    private ActionHistoryService actionHistoryService;
    @Autowired
    private UserInfoForPropertyService userInfoForPropertyService;
    private Logger logger = LogUtils.getBusinessLogger();

    @Autowired
    private Configuration freemarkerConfiguration; // 注入bean，这里是属性注入，推荐构造注入

    /**
     * 住宅房源数据管理列表
     */
    @RequestMapping("houseList")
    @RequiresPermissions("housePersonForProperty:houseList")
    public void houseList(HttpServletRequest request, ModelMap modelMap) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        AzProject azProject = this.azProjectService.findOne(projectId);
        modelMap.addAttribute("azProject", azProject);
    }

    /**
     * 加载房源信息数据
     *
     * @return
     */
    @RequestMapping("loadHouseListForProperty")
    @ResponseBody
    @RequiresPermissions("housePersonForProperty:loadHouseListForProperty")
    public Map loadHouseListForProperty(HttpServletRequest request) {
        List<Map> listData = Lists.newArrayList();
        PageBean<House> housePageBean = this.houseService.getAzStutasHousePageBean();
        List<House> houseList = housePageBean.getDatas();
        Map<String, DataDict> houseTypeMap = this.dataDictService.getMapByParentNameForValue("房屋类型");
        Map<String, DataDict> houseHoldMap = this.dataDictService.getMapByParentNameForValue("房屋户型");
        Map<String, List<Map>> buyHousePersonHouseMap = this.buyHousePersonService.getBuyHousePersonByHouse();
        Map<String, String> housePersonForPropertyListByHouseId = this.housePersonForPropertyService.getHousePersonForPropertyListByHouseId();

        if (!CollectionUtils.isEmpty(houseList)) {
            Map<String, Object> item = null;
            for (House house : houseList) {
                List<Map> buyHousePersonList = buyHousePersonHouseMap.get(house.getId().toString());
                item = null;
                item = Maps.newHashMap();
                item.put("id", house.getId());
                item.put("contractId", house.getContract().getId());
                item.put("azProjectName", StringUtils.getNotNull(house.getAzProject().getProjectName()));
                item.put("buildNum", StringUtils.getNotNull(house.getBuildNum()));
                item.put("houseNum", StringUtils.getNotNull(house.getHouseNum()));
                item.put("floor", house.getFloor());
                item.put("houseTypeStr", StringUtils.dataDictShow(houseTypeMap.get(house.getHouseType())));
                item.put("houseHoldStr", StringUtils.dataDictShow(houseHoldMap.get(house.getHouseHold())));
                item.put("buildArea", BigDecimalUtils.getNotNullStr(house.getBuildArea()));
                item.put("chooseHouseDate", DateUtils.dateToStringDefault(house.getChooseHouseDate()));
                //产权人
                String buyHousePersonName = "";
                String buyHousePersonIdCard = "";
                String buyHousePersonTel = "";
                if (!CollectionUtils.isEmpty(buyHousePersonList)) {
                    for (Map map : buyHousePersonList) {
                        if (buyHousePersonList.size() - 1 == buyHousePersonList.indexOf(map)) {

                            buyHousePersonName = buyHousePersonName + map.get("name");
                            buyHousePersonIdCard = buyHousePersonIdCard + map.get("idCard");
                            buyHousePersonTel = buyHousePersonTel + map.get("tel");
                        } else {
                            buyHousePersonName = buyHousePersonName + map.get("name") + "、";
                            buyHousePersonIdCard = buyHousePersonIdCard + map.get("idCard") + "、";
                            buyHousePersonTel = buyHousePersonTel + map.get("tel") + "、";
                        }
                    }
                }

                item.put("buyHousePersonName", StringUtils.getNotNull(buyHousePersonName));
                item.put("buyHousePersonIdCard", StringUtils.getNotNull(buyHousePersonIdCard));
                item.put("buyHousePersonTel", StringUtils.getNotNull(buyHousePersonTel));
                //减免人
                String housePersonForPropertyName = housePersonForPropertyListByHouseId.get(house.getId().toString());

                item.put("housePersonForPropertyName", StringUtils.getNotNull(housePersonForPropertyName));
                listData.add(item);
            }
        }
        return LayUiUtils.page(housePageBean.getTotalCount().intValue(), listData);
    }

    /**
     * 房源信息导出
     */
    @RequestMapping("housePersonForPropertyListExcel")
    @RequiresPermissions("housePersonForProperty:housePersonForPropertyListExcel")
    public void housePersonForPropertyListExcel(HttpServletRequest request, HttpServletResponse response) {
        PageBean<House> housePageBean = this.houseService.getExcelSelectedHousePageBeanForProperty();
        List<House> houseList = housePageBean.getDatas();
        Map<String, DataDict> houseHoldMap = this.dataDictService.getMapByParentNameForValue("房屋户型");
        Map<String, List<Map>> buyHousePersonHouseMap = this.buyHousePersonService.getBuyHousePersonByHouse();
        Map<String, List<Map>> housePersonForPropertyMap = this.housePersonForPropertyService.getHousePersonForPropertyByHouse();

        try {
            // 封装导出数据
            Map data = Maps.newHashMap();
            data.put("houseList", houseList);
            data.put("houseHoldMap", houseHoldMap);
            data.put("bigUtils", new BigDecimalUtils());
            data.put("buyHousePersonHouseMap", buyHousePersonHouseMap);
            data.put("housePersonForPropertyMap", housePersonForPropertyMap);
            data.put("exportPerson", SecurityUtils.getSubject().getPrincipal());   //导出人姓名
            data.put("exportTime", DateUtils.dateToStringFormat(new Date(), "yyyy-MM-dd HH:mm:ss"));   //导出时间
//            data.put("decisions", exportDecisionList); //第二个worksheet的数据对象
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(("物业减免数据导出.xls").getBytes(), "iso-8859-1"));
            freemarkerConfiguration.getTemplate("/business/property/housePersonForProperty/housePersonForPropertyListExcel.ftl").process(data, response.getWriter());
        } catch (Exception e) {
            logger.error("文件下载异常", e);
            e.printStackTrace();
        }
    }

    /**
     * 房的减免人列表
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("housePersonForPropertyList")
    @RequiresPermissions("housePersonForProperty:housePersonForPropertyList")
    public void housePersonForPropertyList(HttpServletRequest request, ModelMap modelMap) {
        Integer houseId = ParamUtils.getInt(request, "houseId", 0);
        House house = this.houseService.findOne(houseId);
        Precondition.checkSqdsArguement(house != null, "数据错误！");
        modelMap.addAttribute("houseId", houseId);
        modelMap.addAttribute("house", house);
    }

    /**
     * 加载减免人列表数据
     *
     * @return
     */
    @RequestMapping("loadHousePersonForPropertyList")
    @ResponseBody
    @RequiresPermissions("housePersonForProperty:loadHousePersonForPropertyList")
    public Map loadHousePersonForPropertyList(HttpServletRequest request) {
        Integer houseId = ParamUtils.getInt(request, "houseId", 0);
        House house = this.houseService.findOne(houseId);
        Precondition.checkSqdsArguement(house != null, "数据错误！");

        List<Map> listData = Lists.newArrayList();
        PageBean<HousePersonForProperty> housePersonForPropertyPageBean = this.housePersonForPropertyService.housePersonForPropertyPageBeanByHouseId(houseId);
        List<HousePersonForProperty> housePersonForPropertyList = housePersonForPropertyPageBean.getDatas();

        if (!CollectionUtils.isEmpty(housePersonForPropertyList)) {
            Map<String, Object> item = null;
            for (HousePersonForProperty housePersonForProperty : housePersonForPropertyList) {
                item = null;
                item = Maps.newHashMap();
                item.put("housePersonForPropertyId", housePersonForProperty.getId());
                item.put("housePersonForPropertyName", housePersonForProperty.getName());
                item.put("housePersonForPropertyIdCard", housePersonForProperty.getIdCard());
                item.put("housePersonForPropertytel", housePersonForProperty.getTel());
                item.put("relation", housePersonForProperty.getRelation());
                item.put("freeArea", housePersonForProperty.getFreeArea());
                item.put("startDateStr", DateUtils.dateToStringDefault(housePersonForProperty.getStartDate()));
                item.put("stopDateStr", DateUtils.dateToStringDefault(housePersonForProperty.getStopDate()));
                item.put("checkInDateStr", DateUtils.dateToStringDefault(housePersonForProperty.getCheckInDate()));
                item.put("memo", housePersonForProperty.getMemo());

                listData.add(item);
            }
        }
        return LayUiUtils.list(listData);
    }

    /**
     * 减免人数据登记
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("housePersonForPropertyForm")
    @RequiresPermissions("housePersonForProperty:housePersonForPropertyForm")
    public void housePersonForPropertyForm(HttpServletRequest request, ModelMap modelMap) {
        Integer housePersonForPropertyId = ParamUtils.getInt(request, "housePersonForPropertyId", 0);
        Integer houseId = ParamUtils.getInt(request, "houseId", 0);
        House house = this.houseService.findOne(houseId);
        HousePersonForProperty housePersonForProperty = this.housePersonForPropertyService.findOne(housePersonForPropertyId);
        housePersonForProperty = housePersonForProperty == null ? new HousePersonForProperty() : housePersonForProperty;
        modelMap.addAttribute("housePersonForProperty", housePersonForProperty);
        modelMap.addAttribute("house", house);
    }


    /**
     * 减免人员数据保存
     *
     * @param request
     * @return
     * @throws AjaxException
     */
    @RequestMapping("housePersonForPropertySave")
    @ResponseBody
    @RequiresPermissions("housePersonForProperty:housePersonForPropertySave")
    public synchronized Response housePersonForPropertySave(HttpServletRequest request) throws AjaxException {
        return this.housePersonForPropertyService.housePersonForPropertySave(request);
    }


    /**
     * 删除减免人
     *
     * @param request
     * @return
     */
    @RequestMapping("delHousePersonForPropertyById")
    @ResponseBody
    @RequiresPermissions("housePersonForProperty:delHousePersonForPropertyById")
    public synchronized Response delHousePersonForPropertyById(HttpServletRequest request) {
        Integer housePersonForPropertyId = ParamUtils.getInt(request, "housePersonForPropertyId", 0);

        HousePersonForProperty housePersonForProperty = this.housePersonForPropertyService.findOne(housePersonForPropertyId);
        Precondition.checkAjaxArguement(housePersonForProperty != null, "1111", "数据错误！");

        this.housePersonForPropertyService.delete(housePersonForProperty.getId());
        this.actionHistoryService.saveActionHistoryByContractId(housePersonForProperty.getHouse().getContract().getId(),
                "删除房号为" + housePersonForProperty.getHouse().getHouseNumStr() + "的减免人ID为：" + housePersonForProperty.getName(), "删除物业减免人");
        return new Response("0001", "删除成功");
    }


    /**
     * 打印申请表
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("housePersonForPropertyPrint")
    @RequiresPermissions("housePersonForProperty:housePersonForPropertyPrint")
    public void housePersonForPropertyPrint(HttpServletRequest request, ModelMap modelMap) {
        Integer houseId = ParamUtils.getInt(request, "houseId", 0);
        House house = this.houseService.findOne(houseId);
        Precondition.checkSqdsArguement(house != null, "数据错误！未找到房源信息!");
        modelMap.addAttribute("house", house);
    }


    /**
     * 导入物业减免数据页面
     *
     * @param request
     * @param modelMap
     */

    @RequestMapping("importPage")
    @RequiresPermissions("housePersonForProperty:importPage")
    public void importPage(HttpServletRequest request, ModelMap modelMap) {

        Map<String, String> houseTypeMap = this.dataDictService.getMapByParentNameForName_Value("房屋类型");
        modelMap.addAttribute("houseTypeMap", houseTypeMap);
    }


    /**
     * 导入物业减免数据
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Transactional
    @RequestMapping("importHousePersonForProperty")
    @ResponseBody
    @RequiresPermissions("housePersonForProperty:importHousePersonForProperty")
    public Response importHousePersonForProperty(HttpServletRequest request) {

        String housePersonForPropertys = request.getParameter("housePersonForPropertys");
        String[] housePersonForPropertyArray = housePersonForPropertys.split("\r\n");


        //Set<安置项目-幢号-户号-所在层数>
        Map<String, House> houseMap = this.houseService.findHouseMapByAzProjectId();

        String sortNum = null, projectName = null, buildNum = null, floor = null, houseNum = null, buildArea = null, name = null, idCard = null, relation = null,
                freeArea = null, checkInDate = null, startDate = null, stopDate = null, memo = null;

        HousePersonForProperty housePersonForProperty = null;
        //待导入的房源数据
        List<HousePersonForProperty> importHousePersonForPropertyList = new ArrayList<>();

        String[] rowObj = null;
        String houseMapKey = null;
        StringBuffer msg = new StringBuffer();//错误信息
        int errorCount = 0;//错误数据数量
        int rowObjLength = 0;//每条数据的列数
        int index = 0;
        for (String housePersonForPropertyInfo : housePersonForPropertyArray) {
            rowObj = null;
            rowObj = housePersonForPropertyInfo.split("\t");
            rowObjLength = rowObj.length;
            Precondition.checkAjaxArguement(rowObjLength == 14, "0013", "请确认每列都有数据！");
            if (rowObj.length == 0) {
                continue;
            }

            index = 0;
            sortNum = rowObj[index]; //序号
            index++;
            projectName = rowObj[index]; //小区名称
            index++;
            buildNum = rowObj[index]; //幢号
            index++;
            floor = rowObj[index]; //所在层数
            index++;
            houseNum = rowObj[index]; //户号
            index++;
            buildArea = rowObj[index]; //建筑面积
            index++;
            name = rowObj[index]; //减免人
            index++;
            idCard = rowObj[index]; //减免人身份证号
            index++;
            relation = rowObj[index]; //关系
            index++;
            freeArea = rowObj[index]; //减免面积
            index++;
            checkInDate = rowObj[index]; //登记日期
            index++;
            startDate = rowObj[index]; //开始减免日期
            index++;
            stopDate = rowObj[index]; //终止减免时间
            index++;
            memo = rowObj[index]; //备注
            index++;

            houseMapKey = projectName + "-" + buildNum + "-" + houseNum + "-" + floor;

            House house = houseMap.get(houseMapKey);
            if (house == null) {
                errorCount++;
                msg = msg.append("序号" + sortNum + "数据未找到；");
                continue;
            }

            housePersonForProperty = new HousePersonForProperty();

            housePersonForProperty.setHouse(house);
            housePersonForProperty.setName(name);
            housePersonForProperty.setIdCard(idCard);
            housePersonForProperty.setRelation(relation);
            housePersonForProperty.setFreeArea(BigDecimalUtils.stringToBigDecimal(freeArea));
            housePersonForProperty.setCheckInDate(DateUtils.stringToDateDefault(checkInDate));
            housePersonForProperty.setStartDate(DateUtils.stringToDateDefault(startDate));
            housePersonForProperty.setStopDate(DateUtils.stringToDateDefault(stopDate));
            housePersonForProperty.setMemo(memo);

            importHousePersonForPropertyList.add(housePersonForProperty);
        }
        this.housePersonForPropertyService.batchSave(importHousePersonForPropertyList);
        String successInfo = "导入" + importHousePersonForPropertyList.size() + "条减免数据;";
        if (errorCount > 0) {
            successInfo = successInfo + "失败" + errorCount + "条，如下：";
        }
        System.out.println(successInfo + msg.toString());
        Response response = new Response("0001", successInfo + msg.toString());
        return response;

    }


    /**
     * 安置房源统计
     * 各个安置项目房源、车位、储物间选房情况
     */
    @RequestMapping("azStatisticsForFee")
//    @RequiresPermissions("housePersonForProperty:azStatisticsForFee")
    public void azStatisticsForFee(HttpServletRequest request, ModelMap modelMap) {
        String month = ParamUtils.getString(request, "month", "");
        month=month+"-01";
        //安置项目集合
        Map<String, DataDict> townMap = dataDictService.getMapByParentNameForName("乡镇");

        UserInfo userInfo = WebUtils.getLoginUserInfo();
        List<String> azProjectIdList = this.userInfoForPropertyService.findAzProjectIdByUserId(userInfo.getId());
        List<AzProject> azProjectList = this.azProjectService.azProjectListByAzProjectIdList(azProjectIdList);
        Map<String,List<HousePersonForProperty>> housePersonForPropertyMap=this.housePersonForPropertyService.getHousePersonForPropertyByAzProjectId();
        if (CollectionUtils.isNotEmpty(azProjectList)) {
            for (AzProject azProject : azProjectList) {
//这里边把物业减免人的信息循环，然后根据每个安置区累加，看有多少减免的。最后封装map，前台输出

            }
        }

        modelMap.addAttribute("bigUtils", new BigDecimalUtils());
    }


}
